package com.lyz.service;


import com.lyz.entity.OrderEntity;
import com.lyz.feign.HKStockClient;
import com.lyz.mapper.OrderMapper;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@Service
public class OrderService {
    @Autowired
    private OrderMapper mapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HKStockClient hkStockClient;

    @HystrixCommand(fallbackMethod = "saveOrderFallBack")
    public Boolean saveOrder(String userId, String productId, Integer count){
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setCount(count);
        orderEntity.setOrderSn(UUID.randomUUID().toString().replace("-",""));
        orderEntity.setCreateTime(new Date());
        orderEntity.setMoney(new BigDecimal(1000));
        orderEntity.setProductId(productId);
        orderEntity.setUserId(userId);
        orderEntity = mapper.save(orderEntity);
        System.out.println(orderEntity);

        //更新库存
//        try {
//            HttpClient httpClient = HttpClients.createDefault();
//            HttpGet httpGet = new HttpGet("http://localhost:8082/stock/"+productId+"/"+count);
//            HttpResponse response = httpClient.execute(httpGet);
//            boolean b = Boolean.parseBoolean(EntityUtils.toString(response.getEntity()));
//            System.out.println("库存更新结果：" +b);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        Boolean b = restTemplate.getForObject("http://hk-stock/stock/{1}/{2}", Boolean.class, productId, count);
        Boolean b = hkStockClient.updateStock(productId, count);
        System.out.println("修改库存结果：" + b);

        return orderEntity != null;
    }

    //更新库存超时或者发生异常调用兜底方法
    public Boolean saveOrderFallBack(String userId, String productId, Integer count){
        System.out.println("启用了熔断降级方案-saveOrderFallBack:  userId=" + userId + ", productId=" + productId + ", count=" + count);
        return false;
    }
}
